package com.zjitc.service.impl;

import com.zjitc.dao.CartDao;
import com.zjitc.dao.UserDao;
import com.zjitc.model.CartItem;
import com.zjitc.model.Product;
import com.zjitc.model.User;
import com.zjitc.service.CartService;
import com.zjitc.util.CommonUtils;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/5/10 16:04
 * @description:
 */
@Service
public class CartServiceImpl implements CartService {

  @Autowired CartDao cartDao;
  @Autowired UserDao userDao;

  @Override
  public List<CartItem> findByUid(int uid) {

    List<CartItem> list =cartDao.findByUid(uid);
    for (CartItem c: list){
      Product product = cartDao.findByPid(c.getPid());
      User user = userDao.findByUid(c.getUid());
      c.setProduct(product);
      c.setUser(user);
      /*userDao.findUserByUsername(user.getUsername());*/
    }
    return list;
  }

  @Override
  public int addCart(CartItem cartItem) {
    //在增加之前，判断数据库中是否有这个商品条目， pid  uid
    CartItem _cartItem=cartDao.findByPidAndUid(cartItem.getProduct().getPid(),cartItem.getUser().getUid());
    if(_cartItem==null) {
      //没有的话就增加
      cartItem.setCartid(CommonUtils.getUUID());//设置主键
      return cartDao.addCart(cartItem);
    } else {
      //有的话就修改数量
      int total=cartItem.getQuantity()+_cartItem.getQuantity();
      _cartItem.setQuantity(total);
      return cartDao.update(_cartItem);
    }
  }

  @Override
  public void removeCart(String cartid) {
     cartDao.removeCart(cartid);
  }

  @Override
  public void clearCart() {
    cartDao.clearCart();
  }




}
